package com.xxh.securitydemo.filter;

import com.xxh.securitydemo.compoent.AdminUserDetailService;
import com.xxh.securitydemo.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt认证拦截器，在请求头携带jwt的时候，不会走用户名密码认证。
 */
@Component
public class JwtAuthencationFilter  extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    String JwtHead;

    @Autowired
    AdminUserDetailService userDetailService;
    @Autowired
    JWTUtils jwtUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String header = request.getHeader(JwtHead);
        //获取请求头中的token
        if(header !=null){
            logger.info("token:"+header);
            String userName = jwtUtils.getUserNameFromToken(header);
            if(userName!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
                UserDetails details = userDetailService.loadUserByUsername(userName);
                if(jwtUtils.validateToken(header,details)){
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    logger.info("authenticated user:{}"+ userName);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        //一定要放行殴。
        filterChain.doFilter(request,response);
    }
}
